package com.mobile.collect.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;

import com.mobile.collect.R;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.beans.ExportInfo;
import com.mobile.collect.beans.ExportPicInfo;
import com.mobile.collect.beans.ExportResultInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.view.MyPointView;

import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;

public class ExportUtil2 {
    //    Workbook mExcelWorkbook;
    Activity mContext;
    int width;
    int height;
    String exportRecordPath;

    public ExportUtil2(Activity mContext) {
        this.mContext = mContext;
        DisplayMetrics dm = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;
    }

    public void start(final List<DeviceInfo> deviceInfoList) throws Exception {
        export(deviceInfoList);
    }

    public void export(List<DeviceInfo> deviceInfoList) throws Exception {
        NLog.e("ExportUtil", "export");
        String exportPath = Environment.getExternalStorageDirectory() + "/" + mContext.getString(R.string.app_name) + "导出";
        if (AppContents.ISTEST) {
            exportPath = Environment.getExternalStorageDirectory() + "/" + mContext.getString(R.string.app_name) + "/导出/";
            Kits.File.makeFolders(exportPath);
        }
        String exportTime = getNowTimePath();
        String exportWorkPath = exportPath + File.separator + exportTime;
        File file = new File(exportWorkPath);
        file.mkdirs();
        List<ExportResultInfo> exportList = new ArrayList<>();
        for (int i = 0; i < deviceInfoList.size(); i++) {
            ExportResultInfo exportResultInfo = new ExportResultInfo();
            Workbook workbook = new HSSFWorkbook();
            DeviceInfo info = deviceInfoList.get(i);
            info.refresh();

            String sheetName = info.getDeviceName();
            Sheet sheet = workbook.createSheet();
            workbook.setSheetName(0, sheetName);
            setTitleRow(workbook, sheet);
            StringBuilder builder = new StringBuilder(info.getDeviceName());
            if (!TextUtils.isEmpty(info.getDeviceNo())) {
                builder.append("-").append(info.getDeviceNo());
            }

            if (!TextUtils.isEmpty(info.getCreateUser())) {
                builder.append("-").append(info.getCreateUser());
            }
            String deviceDirName = builder.toString();
            File dir = new File(exportWorkPath, deviceDirName);
            dir.mkdir();
            List<ExportPicInfo> exportPicList = null;
            try {
                exportPicList = exportInfo(workbook, sheet, info, dir.getPath());
            } catch (Exception e) {
                e.printStackTrace();
                Kits.File.deleteFile(exportWorkPath);
                throw e;
            }
            File saveFile = new File(dir, deviceDirName + ".xls");
            writeFile(workbook, saveFile.getPath());
            exportResultInfo.setDeviceName(info.getDeviceName());
            exportResultInfo.setPicPathList(exportPicList);
            exportResultInfo.setExcelPath(saveFile.getPath());
            exportResultInfo.setDeviceNum(info.getDeviceNo());
            exportList.add(exportResultInfo);
        }
        ExportInfo exportInfo = new ExportInfo(exportTime);
        long exportInfoId = EntityManager.getInstance().saveExportInfo(exportInfo);
        for (ExportResultInfo exportResultInfo : exportList) {
            exportResultInfo.setParentId(exportInfoId);
            exportResultInfo.setExportTime(exportTime);
        }
        EntityManager.getInstance().saveExportResultInfo(exportList);
        List<ExportPicInfo> exportPicList = new ArrayList<>();
        for (ExportResultInfo exportResultInfo : exportList) {
            NLog.d("rrrr", exportResultInfo.toString());
            for (ExportPicInfo exportPicInfo : exportResultInfo.getPicPathList()) {
                exportPicInfo.setParentId(exportResultInfo.get_ID());
                exportPicList.add(exportPicInfo);
                NLog.d("rrrr", exportPicInfo.toString());
            }
        }
        EntityManager.getInstance().saveExportPicInfo(exportPicList);
    }

    private List<ExportPicInfo> exportInfo(Workbook workbook, Sheet sheet, DeviceInfo deviceInfo, String savePath) throws Exception {
        NLog.e("ExportUtil", "info =" + deviceInfo.getDeviceName());
        int dataRowIndex = 1;
        Font font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        List<ExportPicInfo> exportPicList = new ArrayList<>();

        List<DevicePicInfo> picList = deviceInfo.getDevicePicList();

        Collections.sort(picList, new Comparator<DevicePicInfo>() {
            @Override
            public int compare(DevicePicInfo o1, DevicePicInfo o2) {
                String indexStr = o1.getUnitName()+o1.getDeviceName()+o1.getLabel();
                String index2Str = o2.getUnitName()+o2.getDeviceName()+o2.getLabel();
                if(o2.getSortIndex() > o1.getSortIndex()){
                    return 1;
                }else{
                    return -1;
                }
            }
        });

        for (DevicePicInfo picInfo : picList) {
            writeRecord("开始导出" + deviceInfo.getDeviceName() + "-" + picInfo.getLabel());
            picInfo.refresh();
            String picPaht = picInfo.getPicPath();
            if (!Kits.File.isFileExist(picPaht)) {
                throw new Exception(deviceInfo.getDeviceName() + "-" + picInfo.getLabel() + "导出错误！");
            }
            List<DevicePointInfo> pointList = picInfo.getPointList();
            Collections.sort(pointList, new Comparator<DevicePointInfo>() {
                @Override
                public int compare(DevicePointInfo o1, DevicePointInfo o2) {
                    int result = o1.getExpendNo().compareTo(o2.getExpendNo());
                    return result;
                }
            });
            for (DevicePointInfo pointInfo : pointList) {
                if (pointInfo.getDeviceCount() == 0) {
                    pointInfo.setDeviceCount(1);
                }
                if (pointInfo.getDeviceCount() > 1) {
                    String expendNo = pointInfo.getExpendNo();
                    int startIndex = Integer.parseInt(expendNo);
                    for (int i = 0; i < pointInfo.getDeviceCount(); i++) {
                        Row dataRow = sheet.createRow(dataRowIndex);
                        int index = startIndex + i;
                        pointInfo.setExpendNo(getStartIndex(index));
                        startExPortInfo(workbook, dataRow, deviceInfo, picInfo, pointInfo);
                        dataRowIndex++;
                    }
                } else {
                    Row dataRow = sheet.createRow(dataRowIndex);
                    startExPortInfo(workbook, dataRow, deviceInfo, picInfo, pointInfo);
                    dataRowIndex++;
                }


            }
            String newFileName = deviceInfo.getDeviceNo() + "-" + picInfo.getUnitName() + "-" + picInfo.getLabel();
            String newFilePath = save2File(picInfo, savePath, newFileName);
            if (TextUtils.isEmpty(newFilePath)) {
                throw new Exception(deviceInfo.getDeviceName() + "-" + picInfo.getUnitName()+" 导出失败");
            }
            exportPicList.add(new ExportPicInfo(newFilePath));
        }
        return exportPicList;
    }


    private void startExPortInfo(Workbook workbook, Row dataRow, DeviceInfo deviceInfo, DevicePicInfo picInfo, DevicePointInfo pointInfo) {
        NLog.e("ExportUtil", "startExPortInfo =");
        List<String> valueList = new ArrayList<>();
        valueList.add(deviceInfo.getDeviceName());
        valueList.add(deviceInfo.getDeviceNo() + picInfo.getUnitName());
        valueList.add(picInfo.getDeviceName());
        if (deviceInfo.isMerge()) {
            valueList.add(deviceInfo.getDeviceNo() + picInfo.getUnitName() + picInfo.getLabel());
        } else {
            valueList.add(picInfo.getLabel());
        }
        valueList.add(pointInfo.getExpendNo());

        String deviceNo = deviceInfo.getDeviceNo();
        String unitName = picInfo.getUnitName();
        String label = picInfo.getLabel();
        String groupNo = deviceNo + "-" + unitName + "-" + label;

        valueList.add(groupNo);
        valueList.add(picInfo.getPicNo());
//        valueList.add(pointInfo.getAddressNo());
        valueList.add(picInfo.getReference());
        valueList.add(picInfo.getDirection());
        valueList.add(picInfo.getDistance());
        valueList.add("米");
        valueList.add(picInfo.getFloor());
        valueList.add(pointInfo.getHeight());
        valueList.add("米");
        valueList.add(pointInfo.getAdditionalDes());
        valueList.add(pointInfo.getType());
        valueList.add(pointInfo.getChildType());
        valueList.add(pointInfo.getDiameter());
        String status = pointInfo.getStatus();
        if (TextUtils.isEmpty(status)) {
            status = picInfo.getStatus();
        }
        valueList.add(status);
        valueList.add("");
        valueList.add("");
        valueList.add("");
        valueList.add("");
        valueList.add(TimeUtil.timeStamp2Date(deviceInfo.getEditTime(), "yyyy/MM/dd"));
        valueList.add("");
        valueList.add(pointInfo.getCheckHardType());
        valueList.add(pointInfo.getCheckHardReason());
        valueList.add(pointInfo.getDangerCheck());
        valueList.add(pointInfo.getDangerCheckReaseon());
        valueList.add(pointInfo.getHeatPreservation());
        valueList.add("");
        String newFileName = deviceInfo.getDeviceNo() + "-" + picInfo.getUnitName() + "-" + picInfo.getLabel();
//        String linkName = newFileName+"-"+deviceInfo.getCreateUser();
        String newFlePath = newFileName + ".jpeg";
        valueList.add(newFlePath);
        valueList.add("");
        valueList.add("");
        valueList.add("");
        valueList.add("");
        valueList.add("");
        for (int i = 0; i < valueList.size(); i++) {
            Cell cell = dataRow.createCell(i);
            String value = valueList.get(i);
            NLog.d("xxxx", "i=" + i);
            NLog.d("xxxx", "value=" + value);
            NLog.d("xxxx", "newFlePath=" + newFlePath);

            if (TextUtils.equals(newFlePath, value)) {
                HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
                link.setAddress(newFlePath);
                cell.setHyperlink(link);
                CellStyle linkStyle = workbook.createCellStyle();
                Font ztFont = workbook.createFont();
                ztFont.setColor(IndexedColors.BLUE.getIndex());
                linkStyle.setFont(ztFont);
                cell.setCellStyle(linkStyle);
                cell.setCellValue(newFileName);
            } else {
                cell.setCellType(Cell.CELL_TYPE_STRING);
            }
            cell.setCellValue(value);
        }
    }

    private List<DeviceInfo> getdeviceList() {
        return EntityManager.getInstance().queryAllDeviceInfo();
    }

    private void setTitleRow(Workbook workbook, Sheet sheet) {
        Row titleRow1 = sheet.createRow(0);
        String[] titleRowArray = new String[]{
                "装置全称",
                "单元名称",
                "设备名称",
                "标签",
                "扩展号",
                "群组编码",
                "图号",
                "主要参考物",
                "方向",
                "距离",
                "单位",
                "楼层",
                "高度",
                "单位",
                "附加描述",
                "组件类型",
                "组件子类型",
                "公称直径（mm）",
                "物料状态",
                "产品流",
                "检测配件",
                "变更管理ID",
                "年运行时间/小时",
                "建档时间",
                "开工时间",
                "难于检测",
                "难于检测原因",
                "险于检测",
                "险于检测原因",
                "保温/保冷",
                "密封材质",
                "组件图片",
                "室内",
                "检测路径",
                "是否移除",
                "移除原因",
                "移除时间"};
        for (int t = 0; t < titleRowArray.length; t++) {
            String s = titleRowArray[t];
            if (s.equals("单元名称") || s.equals("群组编码") || "难于检测原因".equals(s)) {
                sheet.setColumnWidth(t, s.length() * 6 * 256);
            } else {
                sheet.setColumnWidth(t, s.length() * 4 * 256);
            }


            Cell cell = titleRow1.createCell(t);
            Font font = workbook.createFont();
            font.setColor(IndexedColors.BLUE.getIndex());
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            CellStyle cStyle = workbook.createCellStyle();
            cStyle.cloneStyleFrom(cell.getCellStyle());
            cStyle.setFont(font);
            cell.setCellStyle(cStyle);
            cell.setCellValue(s);
        }
    }

    public static String getSuffix(String originalFilename) {
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(lastIndexOf);
        return suffix;
    }


    /**
     * 将Excle表格写入文件中
     *
     * @param workbook
     * @param fileName
     */
    private void writeFile(Workbook workbook, String fileName) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fileName);
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (workbook != null) {
                    //workbook.close();
                }
            } catch (Exception e) {
                writeRecord("writeFile--" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public static String getNowTimePath() {
        return TimeUtil.timeStamp2Date(TimeUtil.getNowTimeStampAccuracySecond(), "yyyy-MM-dd_HH-mm-ss");
    }



    //    private String saveFile(DevicePicInfo picInfo, String savePath) {



    private void createResourceBitmap(DevicePicInfo picInfo){
        Bitmap initBitmap = getBitmapFromUri(mContext, picInfo.getPicPath());

        int bgWidth = initBitmap.getWidth();
        int bgHeight = initBitmap.getHeight();

        writeRecord("开始导出" + picInfo.toString());

        writeRecord("当前手机的宽度 =" + width);
        writeRecord("当前手机的高度 =" + height);

        writeRecord("文件读取的原始图片宽度 =" + bgWidth);
        writeRecord("文件读取的原始图片高度 =" + bgHeight);

        int picBitMapWidth = picInfo.getPicBitMapWidth();
        int picBitMapHeight = picInfo.getPicBitmapHeight();

        writeRecord("APP原始图片保存的宽度 =" + picBitMapWidth);
        writeRecord("APP原始图片保存的高度 =" + picBitMapHeight);



        float dx = picBitMapWidth * 1.0f / picBitMapHeight;
        writeRecord("APP原始图片的长宽比例 =" + dx);

        int resultBitMapWeith = width;
        int resultBitMapHeight = (int) (width / dx);

        writeRecord("新图片的宽度 =" + resultBitMapWeith);
        writeRecord("新图片的高度 =" + resultBitMapHeight);

        float pointDx = picBitMapWidth * 1.0f / width;

        Bitmap resourceBitmap = Bitmap.createScaledBitmap(initBitmap, resultBitMapWeith, resultBitMapHeight, true);
        bgWidth = resourceBitmap.getWidth();
        bgHeight = resourceBitmap.getHeight();
        initBitmap.recycle();
    }


    private String save2File(DevicePicInfo picInfo, String dir, String fileName) {
        ExportPicUtil picUtil = new ExportPicUtil(mContext);
       return picUtil.save2File(picInfo,dir,fileName);
    }



    public Bitmap getPoint(final DevicePointInfo pointInfo, int width, int height) {
        MyPointView view;
        String lineType = pointInfo.getLineType2();

        if (TextUtils.equals("1x", lineType)) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point, null, false);
        } else if (TextUtils.equals("2x", lineType)) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point2, null, false);
        } else if (TextUtils.equals("3x", lineType)) {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point3, null, false);
        } else {
            view = (MyPointView) LayoutInflater.from(mContext).inflate(R.layout.layout_img_point, null, false);
        }
        view.setPointInfo(pointInfo, false);

        return createBitmap3(view, width, height);
    }


    public Bitmap getBitmapFromUri(Context context, String outfile) {
        writeRecord("getBitmapFromUri:" + "\n" + outfile);
        try {
//            outfile = outfile.replace("/storage/emulated/0/", "file:///sdcard/");
//            Uri uri = Uri.parse(outfile);
            Uri imageUri;
            File iamgeFile = new File(outfile);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(context, mContext.getPackageName() + ".fileprovider", iamgeFile);
            } else {
                imageUri = Uri.fromFile(iamgeFile);
            }
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
            return bitmap;
        } catch (Exception e) {
            writeRecord("getBitmapFromUri:" + "\n" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public Bitmap createBitmap3(View v, int width, int height) {
        //测量使得view指定大小
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        v.measure(measuredWidth, measuredHeight);
        //调用layout方法布局后，可以得到view的尺寸大小
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        writeRecord("width =" + width + " v.width =" + v.getWidth() + " height=" + height + " v.height =" + v.getHeight());
        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        v.draw(c);
//        bmp.recycle();
        return bmp;
    }

    public boolean saveBitmap(Bitmap bm, File f) {
        writeRecord("saveBitmap =");
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return true;
        } catch (FileNotFoundException e) {
            writeRecord("saveBitmap--" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            writeRecord("saveBitmap--" + e.getMessage());
            e.printStackTrace();
        } finally {
            bm.recycle();
        }
        return false;
    }

    private String getStartIndex(int expend) {
        String expendStr;
        if (expend < 10) {
            expendStr = "00" + expend;
        } else if (expend >= 10 && expend < 100) {
            expendStr = "0" + expend;
        } else {
            expendStr = "" + expend;
        }
        return expendStr;
    }

    private void writeRecord(String message) {
        NLog.d("writeRecord", message);
        if (TextUtils.isEmpty(exportRecordPath)) {
            String root = Environment.getExternalStorageDirectory() + "/" + mContext.getString(R.string.app_name);
            exportRecordPath = root + File.separator + "日志" + File.separator + "导出日志.txt";
            Kits.File.deleteFile(exportRecordPath);
        }
        Kits.File.writeFile(exportRecordPath, message + "\n", true);
    }
//    private String saveFile(DevicePicInfo picInfo, String dir, String fileName) {
//        NLog.e("ExportUtil", "saveFile =");
//        Bitmap initBitmap = getBitmapFromUri(mContext, picInfo.getPicPath());
//
//        int bgWidth = initBitmap.getWidth();
//        int bgHeight = initBitmap.getHeight();
//
//        writeRecord("开始导出" + picInfo.toString());
//
//        writeRecord("当前手机的宽度 =" + width);
//        writeRecord("当前手机的高度 =" + height);
//
//        writeRecord("文件读取的原始图片宽度 =" + bgWidth);
//        writeRecord("文件读取的原始图片高度 =" + bgHeight);
//
//        int picBitMapWidth = picInfo.getPicBitMapWidth();
//        int picBitMapHeight = picInfo.getPicBitmapHeight();
//
//        writeRecord("APP原始图片保存的宽度 =" + picBitMapWidth);
//        writeRecord("APP原始图片保存的高度 =" + picBitMapHeight);
//
//
//
//        float dx = picBitMapWidth * 1.0f / picBitMapHeight;
//        writeRecord("APP原始图片的长宽比例 =" + dx);
//
//        int resultBitMapWeith = width;
//        int resultBitMapHeight = (int) (width / dx);
//
//        writeRecord("新图片的宽度 =" + resultBitMapWeith);
//        writeRecord("新图片的高度 =" + resultBitMapHeight);
//
//        float pointDx = picBitMapWidth * 1.0f / width;
//
//
//        Bitmap resourceBitmap = Bitmap.createScaledBitmap(initBitmap, resultBitMapWeith, resultBitMapHeight, true);
//        bgWidth = resourceBitmap.getWidth();
//        bgHeight = resourceBitmap.getHeight();
//
//        writeRecord("新图片BitMap的宽度 =" + bgWidth);
//        writeRecord("新图片BitMap的高度 =" + bgHeight);
//
//        int minX = 0;
//        int maxX = 0;
//        int minY = (height - bgHeight) / 2;
//        int maxY = 0;
//
//        int lastX = bgWidth;
//        int lastY = bgHeight + minY;
//
//        int iX = (width - bgWidth) / 2;
//        int iY = (height - bgHeight) / 2;
//
//        writeRecord("初始化的 minX" + minX);
//        writeRecord("初始化的 maxX" + maxX);
//        writeRecord("初始化的 minY" + minY);
//        writeRecord("初始化的 maxY" + maxY);
//        writeRecord("初始化的 pointDx" + pointDx);
//
//
//
//        NLog.d("saveFile", "pointCount=" + picInfo.getPointList().size());
//        for (DevicePointInfo pointInfo : picInfo.getPointList()) {
//            NLog.d("saveFile", pointInfo.toString());
//            double scaleX = pointInfo.getScaleX();
//            double scaleY = pointInfo.getScaleY();
//
//            int pointX = (int) (iX + width * scaleX);
//            int pointY = (int) (iY + height * scaleY);
//
//
//
//            NLog.e("TRANSFORM", "pointDx =" + pointDx);
//            NLog.e("TRANSFORM", "oldWidth =" + pointInfo.getViewWidth());
//            NLog.e("TRANSFORM", "oldHeigh =" + pointInfo.getViewHeight());
//
//            writeRecord("转换后点的 screenX =" + pointX);
//            writeRecord("转换后点的 screenY =" + pointY);
//            pointInfo.setScreenX(pointX);
//            pointInfo.setScreenY(pointY);
//
//            int newWidth = (int) (pointInfo.getViewWidth() / pointDx);
//            int newHeigh = (int) (pointInfo.getViewHeight() / pointDx);
//            pointInfo.setViewWidth(newWidth);
//            pointInfo.setViewHeight(newHeigh);
//
//            writeRecord("转换后点的 newWidth =" + newWidth);
//            writeRecord("转换后点的 newHeigh =" + newHeigh);
//
//            if (minX > pointX) {
//                minX = pointX;
//            }
//
//            if (maxX < pointX) {
//                maxX = pointX;
//            }
//
//            if (minY > pointY) {
//                minY = pointY;
//            }
//
//            if (maxY < pointY) {
//                maxY = pointY;
//            }
//
//            if (pointInfo.getDirection() == 0) {
//                pointX = pointX + newWidth;
//            }
//
//            if (lastX == 0 || lastX < pointX) {
//                lastX = pointX;
//            }
//            if (pointInfo.getDirection() == 90) {
//                pointY = pointY + newHeigh;
//            }
//            if (lastY == 0 || lastY < pointY) {
//                lastY = pointY;
//            }
//        }
//
//        writeRecord("lastX =" + lastX);
//        writeRecord("lastY =" + lastY);
//        writeRecord("minX =" + minX);
//        writeRecord("maxX =" + maxX);
//        writeRecord("minY =" + minY);
//        writeRecord("maxY =" + maxY);
//
//
//        int lastWidth = lastX - minX;
//        int lastHeight = lastY;
//        if (minY < 0) {
//            lastHeight = lastY - minY;
//        }
//        if (lastWidth < width) {
//            lastWidth = width;
//        }
//        if (lastHeight < height) {
//            lastHeight = height;
//        }
//
//        Bitmap resultBitmap = Bitmap.createBitmap(lastWidth, lastHeight, Bitmap.Config.ARGB_8888);
//
//        writeRecord("面板的宽度 =" + resultBitmap.getWidth());
//        writeRecord("面板的高度 =" + resultBitmap.getHeight());
//
//        Canvas canvas = new Canvas(resultBitmap);
//
//        int left = Math.abs(minX);
//        int top = Math.abs(minY);
//
//
//        int picPostionX = left;
//        int picPostionY = (height - bgHeight) / 2;
//        writeRecord("面板的高度 picPostionY=" + picPostionY);
//
//        if (minY < 0) {
//            picPostionY = picPostionY - minY;
//        }
//
//        canvas.drawBitmap(resourceBitmap, picPostionX, picPostionY, null);
//
//        int topY = picPostionY;
//        for (DevicePointInfo pointInfo : picInfo.getPointList()) {
//
//            if (pointInfo.getIsNewPoint()) {
//                continue;
//            }
//            Bitmap childBitmap = getPoint(pointInfo, pointInfo.getViewWidth(), pointInfo.getViewHeight());
//            int positionX = pointInfo.getScreenX();
//
//            positionX = picPostionX + positionX;
//
////            if (minX < 0) {
////                positionX = positionX + Math.abs(minX);
////            }
//
////            int positionY = picPostionY+pointInfo.getScreenY();
//            int positionY = picPostionY+pointInfo.getScreenY();
//
//            writeRecord("点的实际坐标X =" + positionX);
//            writeRecord("点的时间坐标Y =" +positionY);
//
//            if (positionY < topY) {
//                topY = positionY;
//            }
//
//            canvas.drawBitmap(childBitmap, positionX, positionY, null);
//            childBitmap.recycle();
//        }
//        Paint textPaint = new Paint();
//        textPaint.setStyle(Paint.Style.FILL);
//        textPaint.setColor(Color.RED);
//        textPaint.setAntiAlias(true);
//        textPaint.setDither(true);
//        textPaint.setStrokeWidth(8);
//        textPaint.setTextSize(50);
//        textPaint.setTextAlign(Paint.Align.LEFT);
//        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
//
//        NLog.d("FontMetrics", "fontMetrics.top=" + fontMetrics.top);
//        NLog.d("FontMetrics", "fontMetrics.bottom=" + fontMetrics.bottom);
//
//        float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
//        canvas.drawText(fileName, picPostionX + 20, picPostionY + 40 + distance, textPaint);
//
//
//        File newFile = new File(dir, fileName + ".jpeg");
//
//
//        int cropWidth = lastX - minX;
//        int cropHeigh = lastY - minY;
//
//        writeRecord("截取的起始点minY =" + minY);
//        writeRecord("截取的宽度 =" + cropWidth);
//        writeRecord("截取的高度 =" +cropHeigh);
//
//        Bitmap result2Bitmap = null;
//        try {
//            result2Bitmap = Bitmap.createBitmap(resultBitmap, 0, topY, cropWidth, cropHeigh);
//            saveBitmap(result2Bitmap, newFile);
//            NLog.d("saveFile", picInfo.getDeviceName() + picInfo.getLabel() + "导出成功");
//            writeRecord(picInfo.getDeviceName() + picInfo.getLabel() + "导出成功");
//        } catch (Exception e) {
//            writeRecord(picInfo.getLabel() + "导出失败\n");
//            NLog.d("saveFile", picInfo.getDeviceName() +picInfo.getDeviceName()+ picInfo.getLabel() + "导出失败");
//            e.printStackTrace();
//            return "";
//
//        }finally {
//            initBitmap.recycle();
//            resourceBitmap.recycle();
//            resultBitmap.recycle();
//            if (null != result2Bitmap) {
//                result2Bitmap.recycle();
//            }
//        }
//        return newFile.getPath();
//    }
}
